<template>
  <el-card>
    <!-- 查询 -->
    <el-form :model="queryParams" inline label-width="80px" class="search-form">
      <el-form-item label="患者姓名">
        <el-input v-model="queryParams.patientName" clearable placeholder="请输入患者姓名" style="width: 150px"/>
      </el-form-item>

      <el-form-item label="医生姓名">
        <el-input v-model="queryParams.doctorName" clearable placeholder="请输入医生姓名" style="width: 150px"/>
      </el-form-item>

      <el-form-item label="手术情况">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option :value="0" label="等待中"/>
          <el-option :value="1" label="已完成"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0" v-loading="loading">
<!--      <el-table-column prop="applicationId" label="申请编号" width="120"/>-->
      <el-table-column prop="patientName" label="姓名" width="120"/>
      <el-table-column prop="doctorName" label="主治医师" width="120"/>
      <el-table-column prop="surgeryName" label="手术" width="180"/>
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{row}">
          ￥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="手术结束时间" width="180">
        <template #default="{row}">
          {{ formatTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{row}">
          <el-button
              v-if="row.status === 0"
              size="small"
              type="success"
              @click="handleComplete(row)">
            完成
          </el-button>
          <el-button
              v-else
              size="small"
              type="info"
              disabled>
            {{ getStatusText(row.status) }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>

    <!-- 完成手术确认弹窗 -->
    <el-dialog title="完成手术" v-model="completeDialogVisible" width="400px">
      <div style="text-align: center;">
        <el-icon size="48" color="#67C23A" style="margin-bottom: 16px;">
          <SuccessFilled />
        </el-icon>
        <p style="font-size: 16px; margin-bottom: 8px;">确认完成该手术吗？</p>
        <p style="color: #909399; font-size: 14px;">
          患者：{{ completeForm.patientName }}<br>
          手术：{{ completeForm.surgeryName }}
        </p>
      </div>
      <template #footer>
        <el-button @click="completeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComplete">确定完成</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import { findPatientSurgery, listPatientSurgery, completeSurgery } from '../api/patientSurgery.js'

export default {
  name: 'PatientSurgeryView',
  components: {
    SuccessFilled
  },
  data() {
    return {
      queryParams: {
        patientName: '',
        doctorName: '',
        status: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      loading: false,
      completeDialogVisible: false,
      completeForm: {
        id: null,
        patientName: '',
        surgeryName: ''
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    async loadData() {
      this.loading = true
      try {
        const hasCondition = this.queryParams.patientName || this.queryParams.doctorName || this.queryParams.status !== ''
        const api = hasCondition ? listPatientSurgery : findPatientSurgery
        const params = {
          ...this.queryParams,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const { data: res } = await api(params)
        if (res.code === 200) {
          this.tableData = res.obj?.list || []
          this.pagination.total = res.obj?.total || 0
        } else {
          ElMessage.error(res.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('请求失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '等待中',
        1: '已完成'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success'
      }
      return typeMap[status] || 'info'
    },
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    },
    handleQuery() {
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleReset() {
      this.queryParams = {
        patientName: '',
        doctorName: '',
        status: ''
      }
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },
    handleComplete(row) {
      this.completeForm = {
        id: row.id,
        patientName: row.patientName,
        surgeryName: row.surgeryName
      }
      this.completeDialogVisible = true
    },
    async submitComplete() {
      try {
        const { data: res } = await completeSurgery({
          id: this.completeForm.id
        })

        if (res.code === 200) {
          ElMessage.success('手术完成')
          this.completeDialogVisible = false
          this.loadData()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } catch (error) {
        console.error('完成手术失败:', error)
        ElMessage.error('操作失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}

:deep(.el-table .cell) {
  word-break: break-word;
}

:deep(.el-tag) {
  margin: 2px;
}
</style>